<template>
	<view>
		<view class="LoginPage">
			<view class="down" @click="handleDown">下载app</view>
			<view class="logo">
				<image class="img" src="/static/images/index/logo.png" mode=""></image>
				<view>欢迎登录</view>
				易联道商城
			</view>
			<view class="form">
				<form @submit="formSubmit">
					<view class="uni-form-item uni-column">
						<view class="title">手机号</view>
						<input class="uni-input" name="account" placeholder="请输入手机号" maxlength="11" />
					</view>
					<view class="uni-form-item uni-column" style="position: relative">
						<view class="title">密码</view>
						<input class="uni-input uni-inputpass" name="password" maxlength="20" placeholder="请输入密码"
							:password="showPassword" />
						<image class="eye"
							:src="showPassword? '/static/images/index/eyes.png': '/static/images/index/openeye.png' "
							mode="" @click="changePassword"></image>
					</view>
					<view class="uni-btn">
						<button form-type="submit" class="uni-btn-v">确认</button>
					</view>
					<!-- 同意服务条款 -->
					<checkbox-group class="auth-clause" @change="CheckboxChange">
						<checkbox class="orange" :class="checked ? 'checked' : ''" :checked="checked ? true : false"
							value="agree" />
						<view>
							同意
							<!-- @tap="onDetails($store.state.common.appConfig.user_agreement,'《易联道商城用户服务协议》',checked_01)" -->
							<text>
								《易联道商城用户服务协议》
							</text>
						</view>
					</checkbox-group>
				</form>
				<view class="goregist">
					<text @tap="register">没有账号,去注册</text>
				</view>
			</view>
		</view>

		<wanl-agree ref="wanl_agree" @agree="onAgree"></wanl-agree>
	</view>
</template>
<script>
	import graceChecker from "@/common/graceChecker";
	import wanlshop_config from '@/common/config/config';
	export default {
		data() {
			return {
				submitDisabled: true,
				providerList: [],
				loginRes: {},
				pageroute: "",
				checked_01: false,
				checked_02: false,
				showPassword: true,
				imgUrl: "",
			};
		},

		async onLoad(option) {
			// // #ifdef H5
			// // 微信内置浏览器登录
			// if (this.$jssdk.isWechat()) {
			// 	let local = window.location.href; // 获取页面url
			// 	let code = this.getUrlCode().code; // 截取code

			// 	// 获取之前的code
			// 	let oldCode = uni.getStorageSync("wanlshop:code");
			// 	// 如果没有code，就去请求获取code
			// 	if (
			// 		code == null ||
			// 		code === "" ||
			// 		code == "undefined" ||
			// 		code == oldCode
			// 	) {
			// 		// 判断有没有同意过用户协议

			// 		const auth_agree = uni.getStorageSync("auth_agree") || 0;
			// 		if (auth_agree) {
			// 			this.wechatOauth2Login(); //微信公众号登录
			// 		} else {
			// 			setTimeout(() => {
			// 				if (this.$store.state.common.appConfig.user_agreement) {
			// 					this.onDetails(
			// 						this.$store.state.common.appConfig.user_agreement,
			// 						"《易联道商城用户服务协议》",
			// 						this.checked_01
			// 					);
			// 				} else {
			// 					setTimeout(() => {
			// 						this.onDetails(
			// 							this.$store.state.common.appConfig.user_agreement,
			// 							"用户协议",
			// 							this.checked_01
			// 						);
			// 					}, 2000);
			// 				}
			// 			}, 1000);
			// 		}
			// 	} else {
			// 		let pageroute = this.getUrlCode().state; // 截取state
			// 		uni.setStorageSync("wanlshop:code", code); // 保存最新code
			// 		await uni.request({
			// 			url: "/wanlshop/user/third",
			// 			method: "POST",
			// 			data: {
			// 				platform: "h5_weixin",
			// 				code: code,
			// 				client_id: uni.getStorageSync("wanlshop:chat_client_id") ?
			// 					uni.getStorageSync("wanlshop:chat_client_id") : null,
			// 			},
			// 			success: (res) => {
			// 				this.$store.dispatch("user/login", res.data);
			// 				this.$store.dispatch("cart/login");
			// 				this.$store.dispatch("chat/get");
			// 				uni.reLaunch({
			// 					url: decodeURIComponent(pageroute)
			// 				});
			// 			},
			// 		});
			// 	}
			// } else {
			// 	let page = this.$wanlshop.prePage().$mp.page;
			// 	this.pageroute = encodeURIComponent(
			// 		`/${page.route}?${this.queryParams(page.options)}`
			// 	);
			// }
			// 未来版本开发
			// this.providerList = [{
			// 	name: 'wlIcon-QQ',
			// 	platform: 'web_qq'
			// }];
			// #endif

			// 获取第三方登录
			// #ifndef H5
			// let page = this.$wanlshop.prePage().$mp.page;
			// this.pageroute = encodeURIComponent(
			// 	`/${page.route}?${this.queryParams(page.options)}`
			// );
			// uni.getProvider({
			// 	service: "oauth",
			// 	success: (res) => {
			// 		this.providerList = res.provider.map((value) => {
			// 			let providerName = "";
			// 			let platform = "";
			// 			switch (value) {
			// 				case "weixin":
			// 					providerName = "wlIcon-WeChat";
			// 					// #ifdef MP
			// 					platform = "mp_weixin";
			// 					// #endif
			// 					// #ifdef APP-PLUS
			// 					platform = "app_weixin";
			// 					// #endif
			// 					break;
			// 				case "qq":
			// 					providerName = "wlIcon-QQ";
			// 					// #ifdef MP
			// 					platform = "mp_qq";
			// 					// #endif
			// 					// #ifdef APP-PLUS
			// 					platform = "app_qq";
			// 					// #endif
			// 					break;
			// 				case "sinaweibo":
			// 					providerName = "wlIcon-WeiBo";
			// 					platform = "app_weibo";
			// 					break;
			// 				case "xiaomi":
			// 					providerName = "wlIcon-Xiaomi";
			// 					platform = "app_xiaomi";
			// 					break;
			// 				case "apple":
			// 					providerName = "wlIcon-Apple";
			// 					platform = "apple";
			// 					break;
			// 			}
			// 			return {
			// 				id: value,
			// 				name: providerName,
			// 				platform: platform,
			// 			};
			// 		});
			// 	},
			// 	fail: (error) => {
			// 		console.log("获取登录通道失败", error);
			// 	},
			// });
			// #endif

			// 防止刷新登录态，uni.login code提前获取
			// #ifdef MP-WEIXIN
			// uni.login({
			// 	provider: "weixin",
			// 	success: (res) => {
			// 		this.loginRes = res;
			// 	},
			// 	fail: (err) => {
			// 		this.$wanlshop.msg(err.msg);
			// 	},
			// });
			// #endif
		},
		computed: {
			checked: function() {
				if (this.checked_01 && this.checked_02) {
					uni.setStorageSync("auth_agree", 1);
					return true;
				}
				return false;
			},
			getSubmitDisabled: function() {
				if (!this.mobile) return true;
				if (!this.checked) return true;
				return false;
			},
		},
		watch: {
			// checked: function(val) {
			// 	if (val && this.$jssdk.isWechat()) {
			// 		//微信内置浏览器
			// 		this.wechatOauth2Login(); //微信公众号登录
			// 	}
			// },
		},
		mounted() {
			// setTimeout(() => {
			//   const auth_agree = uni.getStorageSync("auth_agree") || 0;
			//   if (!auth_agree) {
			//     if (this.$store.state.common.appConfig.user_agreement) {
			//       this.onDetails(
			//         this.$store.state.common.appConfig.user_agreement,
			//         "用户协议",
			//         this.checked_01
			//       );
			//     } else {
			//       setTimeout(() => {
			//         this.onDetails(
			//           this.$store.state.common.appConfig.user_agreement,
			//           "用户协议",
			//           this.checked_01
			//         );
			//       }, 2000);
			//     }
			//   }
			// }, 1000);
		},
		methods: {
			// 登录
			handleSure() {
				uni.request({
					url: wanlshop_config.appurl + "/user/login",
					method: "POST",
					data: {
						account: "",
						password: "",
					},
					success: (res) => {
						this.$store.dispatch("user/login", res.data);
						this.$store.dispatch("cart/login");
						this.$store.dispatch("chat/get");
						uni.reLaunch({
							url: decodeURIComponent(pageroute)
						});
					},
				});
			},
			handleDown() {
				this.$wanlshop.to(`/pages/downApp`);
			},
			changePassword: function() {
				this.showPassword = !this.showPassword;
			},
			CheckboxChange(e) {
				console.log(e)

				if (e.detail.value.length) {
					if (this.f)
						this.checked_01 = true;
					this.checked_02 = true;
					this.onDetails(this.$store.state.common.appConfig.user_agreement, '《易联道商城用户服务协议》', this.checked_01)
				} else {
					this.checked_01 = false;
					this.checked_02 = false;
				}
			},
			onDetails(id, title, checked) {
				this.$refs.wanl_agree.show(id, title, checked);
			},
			onAgree(image) {
				if (image) {
					this.imgUrl = image;
					this.checked_01 = true;
					this.checked_02 = true;
				}
				// if (image == this.$store.state.common.appConfig.user_agreement) {
				//   this.checked_01 = true;
				//   if (!this.checked_02) {
				//     console.log(this.$store.state.common.appConfig.privacy_protection);
				//     this.onDetails(
				//       this.$store.state.common.appConfig.privacy_protection,
				//       "隐私保护",
				//       this.checked_02
				//     );
				//   }
				// }
				// if (image == this.$store.state.common.appConfig.privacy_protection) {
				//   this.checked_02 = true;
				// }
			},
			//微信公众号登录
			wechatOauth2Login() {
				let local = window.location.href; // 获取页面url
				let uri = encodeURIComponent(local);

				// let page = this.$wanlshop.prePage().$mp.page;
				uni.setStorageSync("wanlshop:code", 0); // 设置旧的code为0，避免死循环
				// window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.$wanlshop.config('appid')}&redirect_uri=${uri}&response_type=code&scope=snsapi_userinfo&state=${encodeURIComponent(`/${page.route}?${this.queryParams(page.options)}`)}#wechat_redirect`

				window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.$wanlshop.config(
        "appid"
      )}&redirect_uri=${uri}&response_type=code&scope=snsapi_userinfo&state=${encodeURIComponent(
        `/pages/user`
      )}#wechat_redirect`;
			},
			// 第三方登录
			tologin(provider) {
				uni.showLoading({
					title: "登录中",
				});
				// #ifndef H5
				uni.login({
					provider: provider.id,
					// #ifdef MP-ALIPAY
					scopes: "auth_user", //支付宝小程序需设置授权类型
					// #endif
					success: (loginRes) => {
						uni.request({
							url: "/wanlshop/user/third",
							method: "POST",
							data: {
								platform: provider.platform,
								loginData: loginRes,
								client_id: uni.getStorageSync("wanlshop:chat_client_id") ?
									uni.getStorageSync("wanlshop:chat_client_id") : null,
							},
							success: (res) => {
								uni.hideLoading();
								if (res.data.binding == 0) {
									this.$wanlshop.to(
										`/pages/user/auth/perfect?token=${res.data.token}&platform=${provider.platform}&url=${this.pageroute}`
									);
								} else {
									this.$store.dispatch("user/login", res.data);
									this.$store.dispatch("cart/login");
									this.$store.dispatch("chat/get");
									uni.reLaunch({
										url: decodeURIComponent(this.pageroute)
									});
								}
							},
						});
						// 隐藏键盘
						uni.hideKeyboard();
					},
					fail: (err) => {
						this.$wanlshop.msg(err.msg);
					},
				});
				// #endif
				// #ifdef H5
				uni.request({
					url: "/wanlshop/user/third_web",
					method: "POST",
					data: {
						platform: provider.platform,
						client_id: uni.getStorageSync("wanlshop:chat_client_id") ?
							uni.getStorageSync("wanlshop:chat_client_id") : null,
					},
					success: (res) => {
						uni.hideLoading();
						this.$store.dispatch("user/login", res.data);
						this.$store.dispatch("cart/login");
						this.$store.dispatch("chat/get");
						// 返回页面
						uni.reLaunch({
							url: decodeURIComponent(this.pageroute)
						});
					},
				});
				// #endif
			},
			onKeyInput(e) {
				this.submitDisabled = false;
			},
			// 号码登录，暂时支持微信小程序，后续版本逐渐开发
			async decryptPhoneNumber(e) {
				if (e.detail.errMsg != "getPhoneNumber:fail user deny") {
					await uni.request({
						url: "/wanlshop/user/phone",
						method: "POST",
						data: {
							encryptedData: e.detail.encryptedData,
							iv: e.detail.iv,
							code: this.loginRes.code,
							client_id: uni.getStorageSync("wanlshop:chat_client_id") ?
								uni.getStorageSync("wanlshop:chat_client_id") : null,
						},
						success: (res) => {
							this.$store.dispatch("user/login", res.data);
							this.$store.dispatch("cart/login");
							// 返回页面
							uni.reLaunch({
								url: decodeURIComponent(this.pageroute)
							});
						},
					});
				}
			},
			// 账户登录
			formSubmit(e) {
				if (this.checked) {
					//将下列代码加入到对应的检查位置
					//定义表单规则
					var rule = [{
							name: "account",
							checkType: "phoneno",
							errorMsg: "请输入用户名"
						},
						{
							name: "password",
							checkType: "string",
							checkRule: "6,16",
							errorMsg: "密码至少6位",
						},
					];
					//进行表单检查
					var formData = e.detail.value;
					var checkRes = graceChecker.check(formData, rule);
					console.log(checkRes);
					// ..检查是否注册-没注册跳转注册
					if (!formData.account) {
						return this.$wanlshop.msg("请填写账号");
					} else if (!formData.password) {
						return this.$wanlshop.msg("请填写密码");
					}

					uni.request({
						url: "/user/login",
						method: "POST",
						data: {
							account: formData.account,
							password: formData.password,
							image: this.imgUrl,
						},
						// 1.1.8升级
						complete: (res) => {
							if (res.data.code == 0) {
								uni.showToast({
									icon: "none",
									title: res.data.msg
								})
								// uni.showModal({
								// 	title: "提示",
								// 	content: "账号不存在，是否注册？",
								// 	success: (res) => {
								// 		if (res.confirm) {
								// 			this.$wanlshop.to(
								// 				`register?mobile=${formData.account}&url=${this.pageroute}`
								// 			);
								// 		} else if (res.cancel) {
								// 			console.log("取消");
								// 		}
								// 	},
								// });
							} else {
								this.$store.dispatch("user/login", res.data);
								uni.switchTab({
									url: '/pages/user'
								})
								// 返回页面
								// uni.reLaunch({
								// 	url: decodeURIComponent(this.pageroute)
								// });
							}
						},
					});
				} else {
					setTimeout(() => {
						this.$wanlshop.msg("请先同意用户协议");
					}, 300);
				}
			},
			getUrlCode() {
				// 截取url中的code方法
				var url = location.search;
				// this.winUrl = url;
				var theRequest = new Object();
				if (url.indexOf("?") != -1) {
					var str = url.substr(1);
					var strs = str.split("&");
					for (var i = 0; i < strs.length; i++) {
						theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
					}
				}
				return theRequest;
			},
			register() {
				// ?url=${this.pageroute}
				this.$wanlshop.to(`/pages/user/auth/register`);
			},
			help() {
				this.$wanlshop.to(`/pages/user/help?url=${this.pageroute}`);
			},
			queryParams(data, isPrefix = false) {
				let prefix = isPrefix ? "?" : "";
				let _result = [];
				for (let key in data) {
					let value = data[key];
					// 去掉为空的参数
					if (["", undefined, null].includes(value)) {
						continue;
					}
					if (value.constructor === Array) {
						value.forEach((_value) => {
							_result.push(
								encodeURIComponent(key) + "[]=" + encodeURIComponent(_value)
							);
						});
					} else {
						_result.push(
							encodeURIComponent(key) + "=" + encodeURIComponent(value)
						);
					}
				}
				return _result.length ? prefix + _result.join("&") : "";
			},
		},
	};
</script>

<style lang="scss" scoped>
	@import url("auth.css");

	page {
		background: #fff;
	}

	.LoginPage {
		width: 100%;
		height: calc(100vh - 44px);
		background-image: url("/static/images/index/bg.png");
		background-repeat: no-repeat;
		background-position: center bottom;
		background-size: 100% 242rpx;
		// overflow: hidden;
		padding-top: 40rpx;

		.down {
			color: #666666;
			font-size: 28rpx;
			position: absolute;
			top: 0;
			right: 20rpx;
		}

		.logo {
			width: 162rpx;
			height: 162rpx;
			margin: 0 auto;
			font-weight: 500;
			font-size: 32rpx;
			color: #333333;
			text-align: center;

			.img {
				width: 152rpx;
				height: 152rpx;
				margin-bottom: 36rpx;
			}
		}

		.form {
			padding: 0 24rpx;
			margin-top: 160rpx;
			clear: both;

			.uni-input {
				height: 96rpx;
				line-height: 96rpx;
				background: #f8f8f8;
				padding: 0 30rpx;
				margin-top: 20rpx;
				border-radius: 16rpx;
			}
		}

		.uni-form-item {
			margin-top: 20rpx;

			.title {
				font-family: PingFang SC, PingFang SC;
				font-weight: 400;
				font-size: 28rpx;
				color: #333333;
			}

			.eye {
				width: 40rpx;
				height: 40rpx;
				position: absolute;
				right: 30rpx;
				top: 86rpx;
			}
		}

		.uni-btn-v {
			width: 702rpx;
			height: 96rpx;
			background: #327CFF;
			border-radius: 16rpx 16rpx 16rpx 16rpx;
			margin-top: 40rpx;
			font-weight: 400;
			font-size: 28rpx;
			color: #ffffff;
			line-height: 96rpx;
		}

		.goregist {
			font-weight: 400;
			font-size: 28rpx;
			color: #666666;
			text-align: center;
			margin-top: 152rpx;
		}
	}
</style>